package org.nf.trading.service.app.message.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.nf.trading.dao.MessageMapper;
import org.nf.trading.dto.ChatMessageDTO;
import org.nf.trading.dto.MessageDTO;
import org.nf.trading.service.app.message.exception.MessageDataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@ServerEndpoint(value = "/chat", configurator = HandShakeConfigurator.class)
//@Data
public class ChatNotifyWebSocketServerHandler {
    @Autowired
    private MessageMapper messageMapper;

    /**
     * 用户保存所有的用户
     */
    private static Map<String,Session> clients = new HashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        //获取登录的用户
        String userId = (String)session.getUserProperties().get("userId");
        System.out.println("当前用户为：" + userId);
        clients.put(userId, session);
        clients.forEach((k,v) -> {
            System.out.println("在线用户=====> "+k);
        });
    }

    /**
     * 用户离线移除在线列表
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        String userId = (String) session.getUserProperties().get("userId");
        log.info(userId + "已离线");
        //从用户列表移除这个用户
        clients.remove(userId);
        clients.forEach((k,v) -> {
            System.out.println("离线用户=====> "+k);
        });
    }

    public void chatSend(ChatMessageDTO chatMessageDTO){
        if (clients.containsKey(chatMessageDTO.getReceiverId())) {
            chatMessageDTO.setType("2");
            // 发送消息
            try {
                String s = new ObjectMapper().writeValueAsString(chatMessageDTO);
                clients.get(chatMessageDTO.getReceiverId()).getBasicRemote().sendText(s);
            } catch (IOException e) {
                e.printStackTrace();
                throw new MessageDataException(500,"消息发送失败");
            }
        }
    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket 连接出现异常: {}", throwable);
        // 可以选择关闭连接等操作
        try {
            session.close();
        } catch (IOException e) {
            log.error("关闭 WebSocket 连接出现异常: {}", e.getMessage());
        }
    }

}
